using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Diagnostics;
using System.Threading;

namespace SimpleTongHuaShunQuery
{
    /// <summary>
    /// 简化版查询资金股票程序
    /// </summary>
    class QueryFundsStocksSimple
    {
        #region Windows API 声明
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern IntPtr CreateToolhelp32Snapshot(uint dwFlags, uint th32ProcessID);

        [DllImport("kernel32.dll")]
        static extern bool Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);

        [DllImport("kernel32.dll")]
        static extern bool Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool CloseHandle(IntPtr hObject);

        [DllImport("user32.dll")]
        static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);

        [DllImport("user32.dll")]
        static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

        [DllImport("user32.dll")]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

        [DllImport("user32.dll")]
        static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

        [DllImport("user32.dll")]
        static extern bool IsWindowVisible(IntPtr hWnd);

        [DllImport("user32.dll")]
        static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        [DllImport("user32.dll")]
        static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

        [DllImport("user32.dll")]
        static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);

        [DllImport("user32.dll")]
        static extern bool EnumChildWindows(IntPtr hWndParent, EnumChildProc lpEnumFunc, IntPtr lParam);

        [DllImport("user32.dll")]
        static extern int GetDlgCtrlID(IntPtr hWndCtl);


        [DllImport("user32.dll")]
        static extern bool SetCursorPos(int x, int y);

        [DllImport("user32.dll")]
        static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, UIntPtr dwExtraInfo);

        [DllImport("user32.dll")]
        static extern bool OpenClipboard(IntPtr hWndNewOwner);

        [DllImport("user32.dll")]
        static extern bool CloseClipboard();

        [DllImport("user32.dll")]
        static extern IntPtr GetClipboardData(uint uFormat);

        [DllImport("user32.dll")]
        static extern bool EmptyClipboard();

        [DllImport("kernel32.dll")]
        static extern IntPtr GlobalLock(IntPtr hMem);

        [DllImport("kernel32.dll")]
        static extern bool GlobalUnlock(IntPtr hMem);

        [DllImport("user32.dll")]
        static extern IntPtr GetDC(IntPtr hWnd);

        [DllImport("user32.dll")]
        static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);

        [DllImport("gdi32.dll")]
        static extern IntPtr CreateCompatibleDC(IntPtr hDC);

        [DllImport("gdi32.dll")]
        static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth, int nHeight);

        [DllImport("gdi32.dll")]
        static extern IntPtr SelectObject(IntPtr hDC, IntPtr hGDIObj);

        [DllImport("gdi32.dll")]
        static extern bool BitBlt(IntPtr hDestDC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, uint dwRop);

        [DllImport("gdi32.dll")]
        static extern bool DeleteDC(IntPtr hDC);

        [DllImport("gdi32.dll")]
        static extern bool DeleteObject(IntPtr hObject);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        static extern uint GetTempPath(uint nBufferLength, StringBuilder lpBuffer);

        [DllImport("gdi32.dll")]
        static extern uint GetDIBits(IntPtr hdc, IntPtr hbmp, uint uStartScan, uint cScanLines, IntPtr lpvBits, ref BITMAPINFO lpbi, uint uUsage);

        const int SW_RESTORE = 9;
        const int SW_SHOW = 5;
        const uint TH32CS_SNAPPROCESS = 0x00000002;
        const uint WM_CLOSE = 0x0010;
        const uint WM_SETTEXT = 0x000C;
        const uint BM_CLICK = 0x00F5;
        
        // 键盘事件
        const uint KEYEVENTF_KEYUP = 0x0002;
        const byte VK_F4 = 0x73;
        const byte VK_F5 = 0x74;
        const byte VK_CONTROL = 0x11;
        const byte VK_A = 0x41;
        const byte VK_C = 0x43;
        const byte VK_DELETE = 0x2E;
        
        // 数字键
        const byte VK_0 = 0x30;
        const byte VK_1 = 0x31;
        const byte VK_2 = 0x32;
        const byte VK_3 = 0x33;
        const byte VK_4 = 0x34;
        const byte VK_5 = 0x35;
        const byte VK_6 = 0x36;
        const byte VK_7 = 0x37;
        const byte VK_8 = 0x38;
        const byte VK_9 = 0x39;

        // 剪贴板格式
        const uint CF_TEXT = 1;

        // BitBlt操作码
        const uint SRCCOPY = 0x00CC0020;

        // DIB颜色表
        const uint DIB_RGB_COLORS = 0;

        [StructLayout(LayoutKind.Sequential)]
        public struct PROCESSENTRY32
        {
            public uint dwSize;
            public uint cntUsage;
            public uint th32ProcessID;
            public IntPtr th32DefaultHeapID;
            public uint th32ModuleID;
            public uint cntThreads;
            public uint th32ParentProcessID;
            public int pcPriClassBase;
            public uint dwFlags;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szExeFile;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int Left, Top, Right, Bottom;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct BITMAPINFOHEADER
        {
            public uint biSize;
            public int biWidth;
            public int biHeight;
            public ushort biPlanes;
            public ushort biBitCount;
            public uint biCompression;
            public uint biSizeImage;
            public int biXPelsPerMeter;
            public int biYPelsPerMeter;
            public uint biClrUsed;
            public uint biClrImportant;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct BITMAPINFO
        {
            public BITMAPINFOHEADER bmiHeader;
        }

        public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
        public delegate bool EnumChildProc(IntPtr hWnd, IntPtr lParam);
        #endregion

        static void Main(string[] args)
        {
            Console.WriteLine("🚀 简化版同花顺查询程序 - 资金股票查询");
            Console.WriteLine("📋 新的简化流程:");
            Console.WriteLine("   1. 连接GUI程序");
            Console.WriteLine("   2. 关掉可能出现的对话框");
            Console.WriteLine("   3. 发送热键F4");
            Console.WriteLine("   4. 定位AutomationId=1047控件并复制内容");
            Console.WriteLine("   5. 读取并显示剪贴板内容");
            Console.WriteLine();

            try
            {
                // 执行简化的查询流程
                ExecuteSimpleQuery();
            }
            catch (Exception ex)
            {
                Console.WriteLine("❌ 程序异常: " + ex.Message);
                Console.WriteLine("按任意键退出...");
                Console.ReadKey();
            }
        }

        /// <summary>
        /// 执行简化的查询流程
        /// </summary>
        static void ExecuteSimpleQuery()
        {
            try
            {
                Console.WriteLine("🚀 开始执行简化查询流程");
                
                // 预备步骤：清空剪贴板
                Console.WriteLine();
                Console.WriteLine("🔍 预备步骤: 清空剪贴板");
                bool clearSuccess = ClearClipboard();
                if (clearSuccess)
                {
                    Console.WriteLine("✅ 剪贴板清空成功");
                }
                else
                {
                    Console.WriteLine("⚠️ 剪贴板清空失败，继续执行");
                }
                
                // 第一步：连接GUI程序
                Console.WriteLine();
                Console.WriteLine("🔍 第一步: 连接GUI程序");
                uint processId = ConnectToGUI();
                if (processId == 0)
                {
                    Console.WriteLine("❌ 连接GUI失败");
                    return;
                }
                Console.WriteLine("✅ GUI连接成功，PID: " + processId);

                // 第二步：关掉可能出现的对话框
                Console.WriteLine();
                Console.WriteLine("🔍 第二步: 关掉可能出现的对话框");
                int closedCount = ClosePopupDialogs(processId);
                Console.WriteLine("✅ 关闭了 " + closedCount + " 个对话框");

                // 激活主窗口
                Console.WriteLine();
                Console.WriteLine("🔍 激活主窗口");
                IntPtr mainWindow = FindAndActivateMainWindow(processId);
                if (mainWindow == IntPtr.Zero)
                {
                    Console.WriteLine("❌ 未找到或激活主窗口失败");
                    return;
                }
                Console.WriteLine("✅ 主窗口激活成功");

                // 第三步：发送热键F4
                Console.WriteLine();
                Console.WriteLine("🔍 第三步: 发送热键F4");
                bool f4Success = SendF4Hotkey();
                if (!f4Success)
                {
                    Console.WriteLine("❌ F4热键发送失败");
                    return;
                }
                Console.WriteLine("✅ F4热键发送成功");

                // 第三步补充：发送热键F5
                Console.WriteLine();
                Console.WriteLine("🔍 第三步补充: 发送热键F5");
                bool f5Success = SendF5Hotkey();
                if (!f5Success)
                {
                    Console.WriteLine("❌ F5热键发送失败");
                    return;
                }
                Console.WriteLine("✅ F5热键发送成功");

                // 第四步：定位AutomationId=1047控件并复制内容
                Console.WriteLine();
                Console.WriteLine("🔍 第四步: 定位AutomationId=1047控件并复制内容");
                bool copySuccess = FindControlAndCopyContent(mainWindow, processId);
                if (!copySuccess)
                {
                    Console.WriteLine("❌ 控件内容复制失败");
                    return;
                }
                Console.WriteLine("✅ 控件内容复制成功");

                // 第五步：读取并显示剪贴板内容
                Console.WriteLine();
                Console.WriteLine("🔍 第五步: 读取并显示剪贴板内容");
                string clipboardContent = ReadClipboardText();
                if (!string.IsNullOrEmpty(clipboardContent))
                {
                    Console.WriteLine("✅ 剪贴板内容读取成功");
                    Console.WriteLine();
                    Console.WriteLine("📋 剪贴板内容:");
                    Console.WriteLine("" + new string('=', 50));
                    Console.WriteLine(clipboardContent);
                    Console.WriteLine("" + new string('=', 50));
                    Console.WriteLine("🎉 完整查询流程完成！");
                }
                else
                {
                    Console.WriteLine("❌ 剪贴板内容为空或读取失败");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("❌ 执行简化查询异常: " + ex.Message);
            }
            finally
            {
                Console.WriteLine();
                Console.WriteLine("📝 简化查询流程处理完成");
                // 程序直接退出，不需要按任意键
            }
        }

        /// <summary>
        /// 第一步：连接GUI程序
        /// </summary>
        static uint ConnectToGUI()
        {
            Console.WriteLine("🔍 正在查找xiadan.exe进程...");
            
            uint processId = FindProcessByName("xiadan.exe");
            if (processId == 0)
            {
                Console.WriteLine("❌ 未找到xiadan.exe进程");
                Console.WriteLine("💡 请确保同花顺程序正在运行");
                return 0;
            }

            Console.WriteLine("✅ 找到xiadan.exe进程，PID: " + processId);
            return processId;
        }

        /// <summary>
        /// 第二步：关掉可能出现的对话框
        /// </summary>
        static int ClosePopupDialogs(uint processId)
        {
            Console.WriteLine("🔍 正在查找并关闭弹出对话框...");
            int closedCount = 0;

            EnumWindows((hWnd, lParam) =>
            {
                uint windowProcessId;
                GetWindowThreadProcessId(hWnd, out windowProcessId);
                
                if (windowProcessId == processId && IsWindowVisible(hWnd))
                {
                    StringBuilder className = new StringBuilder(256);
                    GetClassName(hWnd, className, className.Capacity);
                    string windowClass = className.ToString();

                    StringBuilder title = new StringBuilder(256);
                    GetWindowText(hWnd, title, title.Capacity);
                    string windowTitle = title.ToString();

                    // 关闭类型为#32770的对话框（但不关闭主窗口）
                    if (windowClass == "#32770" && !windowTitle.Contains("网上股票交易系统"))
                    {
                        Console.WriteLine("🗑️ 关闭弹出框: \"" + windowTitle + "\"");
                        SendMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
                        closedCount++;
                    }
                }
                return true;
            }, IntPtr.Zero);

            return closedCount;
        }

        /// <summary>
        /// 查找并激活主窗口
        /// </summary>
        static IntPtr FindAndActivateMainWindow(uint processId)
        {
            Console.WriteLine("🔍 正在查找主窗口...");
            IntPtr mainWindow = IntPtr.Zero;

            EnumWindows((hWnd, lParam) =>
            {
                uint windowProcessId;
                GetWindowThreadProcessId(hWnd, out windowProcessId);
                
                if (windowProcessId == processId && IsWindowVisible(hWnd))
                {
                    StringBuilder title = new StringBuilder(256);
                    GetWindowText(hWnd, title, title.Capacity);
                    string windowTitle = title.ToString();

                    if (windowTitle.Contains("网上股票交易系统"))
                    {
                        Console.WriteLine("📋 找到主窗口: \"" + windowTitle + "\"");
                        mainWindow = hWnd;
                        return false; // 停止枚举
                    }
                }
                return true;
            }, IntPtr.Zero);

            if (mainWindow != IntPtr.Zero)
            {
                // 激活主窗口
                Console.WriteLine("🔄 正在激活主窗口...");
                
                // 检查窗口是否最小化
                RECT mainRect;
                if (GetWindowRect(mainWindow, out mainRect))
                {
                    if (mainRect.Left < -1000 || mainRect.Top < -1000)
                    {
                        Console.WriteLine("⚠️ 检测到窗口被最小化，正在恢复...");
                        ShowWindow(mainWindow, SW_RESTORE);
                    }
                }
                
                ShowWindow(mainWindow, SW_SHOW);
                SetForegroundWindow(mainWindow);
               
                
                Console.WriteLine("✅ 主窗口激活完成");
            }

            return mainWindow;
        }

        /// <summary>
        /// 第三步：发送热键F4
        /// </summary>
        static bool SendF4Hotkey()
        {
            try
            {
                Console.WriteLine("⌨️ 正在发送F4热键...");
                
                // 发送F4按键
                keybd_event(VK_F4, 0, 0, UIntPtr.Zero); // 按下F4
                keybd_event(VK_F4, 0, KEYEVENTF_KEYUP, UIntPtr.Zero); // 释放F4
                
                
                Console.WriteLine("✅ F4热键发送完成");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("❌ 发送F4热键异常: " + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 发送热键F5
        /// </summary>
        static bool SendF5Hotkey()
        {
            try
            {
                Console.WriteLine("⌨️ 正在发送F5热键...");
                
                // 发送F5按键
                keybd_event(VK_F5, 0, 0, UIntPtr.Zero); // 按下F5
                keybd_event(VK_F5, 0, KEYEVENTF_KEYUP, UIntPtr.Zero); // 释放F5
                
                Thread.Sleep(100);
                Console.WriteLine("✅ F5热键发送完成");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("❌ 发送F5热键异常: " + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 根据进程名查找进程ID
        /// </summary>
        static uint FindProcessByName(string processName)
        {
            IntPtr hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
            if (hProcessSnap == IntPtr.Zero)
                return 0;

            PROCESSENTRY32 pe32 = new PROCESSENTRY32();
            pe32.dwSize = (uint)Marshal.SizeOf(typeof(PROCESSENTRY32));

            if (!Process32First(hProcessSnap, ref pe32))
            {
                CloseHandle(hProcessSnap);
                return 0;
            }

            do
            {
                if (pe32.szExeFile.Equals(processName, StringComparison.OrdinalIgnoreCase))
                {
                    CloseHandle(hProcessSnap);
                    return pe32.th32ProcessID;
                }
            } while (Process32Next(hProcessSnap, ref pe32));

            CloseHandle(hProcessSnap);
            return 0;
        }

        /// <summary>
        /// 第四步：查找AutomationId=1047控件并复制内容
        /// </summary>
        static bool FindControlAndCopyContent(IntPtr mainWindow, uint processId)
        {
            try
            {
                Console.WriteLine("🔍 正在查找AutomationId=1047的控件...");
                
                
                IntPtr targetControl = FindControlByAutomationId(mainWindow, 1047);
                if (targetControl == IntPtr.Zero)
                {
                    Console.WriteLine("❌ 未找到AutomationId=1047的控件");
                    return false;
                }
                
                Console.WriteLine("✅ 找到AutomationId=1047控件 (句柄: 0x" + targetControl.ToString("X") + ")");
                
                // 设置焦点到目标控件 - 使用鼠标点击
                Console.WriteLine("🎯 设置焦点到目标控件...");
                RECT targetRect;
                if (GetWindowRect(targetControl, out targetRect))
                {
                    int centerX = (targetRect.Left + targetRect.Right) / 2;
                    int centerY = (targetRect.Top + targetRect.Bottom) / 2;
                    
                    SetCursorPos(centerX, centerY);
                    mouse_event(0x0002, 0, 0, 0, UIntPtr.Zero); // MOUSEEVENTF_LEFTDOWN
                    mouse_event(0x0004, 0, 0, 0, UIntPtr.Zero); // MOUSEEVENTF_LEFTUP
                    Console.WriteLine("✅ 焦点设置成功");
                }
                else
                {
                    Console.WriteLine("⚠️ 无法获取控件位置");
                }
    
                
                // 发送Ctrl+A（全选）
                Console.WriteLine("⌨️ 发送Ctrl+A（全选）...");
                SendCtrlA();
              
                
                // 发送Ctrl+C（复制）
                Console.WriteLine("⌨️ 发送Ctrl+C（复制）...");
                SendCtrlC();
                Thread.Sleep(100);
                
                // 检查是否出现对话框
                Console.WriteLine("🔍 检查是否出现对话框...");
                bool hasDialog = CheckForDialog(processId);
                if (hasDialog)
                {
                    Console.WriteLine("⚠️ 检测到对话框，可能需要处理");
                    // 可以选择关闭对话框或记录信息
                }
                else
                {
                    Console.WriteLine("✅ 未检测到对话框");
                }
                
                Console.WriteLine("✅ 控件内容已复制到剪贴板");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("❌ 查找控件并复制内容异常: " + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 通过AutomationId查找控件
        /// </summary>
        static IntPtr FindControlByAutomationId(IntPtr parentWindow, int automationId)
        {
            IntPtr result = IntPtr.Zero;
            
            Console.WriteLine("🔍 在主窗口中搜索AutomationId=" + automationId + "的控件...");
            
            // 直接枚举子窗口
            EnumChildWindows(parentWindow, (hWnd, lParam) =>
            {
                int controlId = GetDlgCtrlID(hWnd);
                
                if (controlId == automationId)
                {
                    StringBuilder className = new StringBuilder(256);
                    GetClassName(hWnd, className, className.Capacity);
                    string controlClass = className.ToString();
                    
                    Console.WriteLine("✅ 找到匹配控件: AutomationId=" + controlId + ", 类型=" + controlClass);
                    result = hWnd;
                    return false; // 停止枚举
                }
                return true;
            }, IntPtr.Zero);
            
            // 如果直接子窗口没找到，递归搜索
            if (result == IntPtr.Zero)
            {
                Console.WriteLine("🔍 在子窗口中递归搜索...");
                EnumChildWindows(parentWindow, (hWnd, lParam) =>
                {
                    IntPtr childResult = FindControlByAutomationId(hWnd, automationId);
                    if (childResult != IntPtr.Zero)
                    {
                        result = childResult;
                        return false; // 停止枚举
                    }
                    return true;
                }, IntPtr.Zero);
            }
            
            return result;
        }

        /// <summary>
        /// 发送Ctrl+A热键（全选）
        /// </summary>
        static void SendCtrlA()
        {
            keybd_event(VK_CONTROL, 0, 0, UIntPtr.Zero); // 按下Ctrl
            keybd_event(VK_A, 0, 0, UIntPtr.Zero); // 按下A
            keybd_event(VK_A, 0, KEYEVENTF_KEYUP, UIntPtr.Zero); // 释放A
            keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, UIntPtr.Zero); // 释放Ctrl
        }

        /// <summary>
        /// 发送Ctrl+C热键（复制）
        /// </summary>
        static void SendCtrlC()
        {
            keybd_event(VK_CONTROL, 0, 0, UIntPtr.Zero); // 按下Ctrl

            keybd_event(VK_C, 0, 0, UIntPtr.Zero); // 按下C

            keybd_event(VK_C, 0, KEYEVENTF_KEYUP, UIntPtr.Zero); // 释放C

            keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, UIntPtr.Zero); // 释放Ctrl
        }

        /// <summary>
        /// 读取剪贴板文本内容
        /// </summary>
        static string ReadClipboardText()
        {
            try
            {
                Console.WriteLine("📋 正在读取剪贴板内容...");
                
                if (!OpenClipboard(IntPtr.Zero))
                {
                    Console.WriteLine("❌ 无法打开剪贴板");
                    return "";
                }

                IntPtr hData = GetClipboardData(CF_TEXT);
                if (hData == IntPtr.Zero)
                {
                    Console.WriteLine("❌ 剪贴板中没有文本数据");
                    CloseClipboard();
                    return "";
                }

                IntPtr pData = GlobalLock(hData);
                if (pData == IntPtr.Zero)
                {
                    Console.WriteLine("❌ 无法锁定剪贴板数据");
                    CloseClipboard();
                    return "";
                }

                string text = Marshal.PtrToStringAnsi(pData);
                
                GlobalUnlock(hData);
                CloseClipboard();
                
                Console.WriteLine("✅ 剪贴板内容读取完成，长度: " + (text != null ? text.Length : 0) + " 字符");
                return text != null ? text : "";
            }
            catch (Exception ex)
            {
                Console.WriteLine("❌ 读取剪贴板异常: " + ex.Message);
                try
                {
                    CloseClipboard();
                }
                catch { }
                return "";
            }
        }

        /// <summary>
        /// 清空剪贴板内容
        /// </summary>
        static bool ClearClipboard()
        {
            try
            {
                Console.WriteLine("🗑️ 正在清空剪贴板...");
                
                if (!OpenClipboard(IntPtr.Zero))
                {
                    Console.WriteLine("❌ 无法打开剪贴板进行清空操作");
                    return false;
                }

                bool success = EmptyClipboard();
                CloseClipboard();
                
                if (success)
                {
                    Console.WriteLine("✅ 剪贴板已清空");
                    return true;
                }
                else
                {
                    Console.WriteLine("❌ 剪贴板清空失败");
                    return false;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("❌ 清空剪贴板异常: " + ex.Message);
                try
                {
                    CloseClipboard();
                }
                catch { }
                return false;
            }
        }

        /// <summary>
        /// 检查是否出现#32770类型的对话框
        /// </summary>
        static bool CheckForDialog(uint processId)
        {
            try
            {
                bool foundDialog = false;
                
                EnumWindows((hWnd, lParam) =>
                {
                    uint windowProcessId;
                    GetWindowThreadProcessId(hWnd, out windowProcessId);
                    
                    if (windowProcessId == processId && IsWindowVisible(hWnd))
                    {
                        StringBuilder className = new StringBuilder(256);
                        GetClassName(hWnd, className, className.Capacity);
                        string windowClass = className.ToString();

                        if (windowClass == "#32770")
                        {
                            StringBuilder title = new StringBuilder(256);
                            GetWindowText(hWnd, title, title.Capacity);
                            string windowTitle = title.ToString();
                            
                            Console.WriteLine("🔍 发现#32770对话框: \"" + windowTitle + "\"");
                            foundDialog = true;
                            
                            // 查找并获取AutomationId=2405的Image控件
                            Console.WriteLine("🖼️ 正在查找AutomationId=2405的Image控件...");
                            bool imageSuccess = CaptureImageControl(hWnd);
                            if (imageSuccess)
                            {
                                Console.WriteLine("✅ 成功获取Image控件信息");
                            }
                            else
                            {
                                Console.WriteLine("❌ 未找到或获取Image控件失败");
                            }
                            
                            // 可以选择关闭这个对话框
                            // SendMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
                            // Console.WriteLine("🗑️ 已关闭对话框: \"" + windowTitle + "\"");
                        }
                    }
                    return true; // 继续枚举所有窗口
                }, IntPtr.Zero);
                
                return foundDialog;
            }
            catch (Exception ex)
            {
                Console.WriteLine("❌ 检查对话框异常: " + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 在对话框中查找并获取AutomationId=2405的Image控件
        /// </summary>
        static bool CaptureImageControl(IntPtr dialogWindow)
        {
            try
            {
                // 查找AutomationId=2405的控件
                IntPtr imageControl = FindControlByAutomationId(dialogWindow, 2405);
                if (imageControl == IntPtr.Zero)
                {
                    Console.WriteLine("❌ 未找到AutomationId=2405的控件");
                    return false;
                }

                // 获取控件的类名验证是否为Image类型
                StringBuilder className = new StringBuilder(256);
                GetClassName(imageControl, className, className.Capacity);
                string controlClass = className.ToString();
                Console.WriteLine("📋 找到控件类型: " + controlClass);

                // 获取控件位置和尺寸
                RECT controlRect;
                if (!GetWindowRect(imageControl, out controlRect))
                {
                    Console.WriteLine("❌ 无法获取Image控件位置");
                    return false;
                }

                int width = controlRect.Right - controlRect.Left;
                int height = controlRect.Bottom - controlRect.Top;
                Console.WriteLine("📏 Image控件尺寸: " + width + "x" + height);
                Console.WriteLine("📍 Image控件位置: [" + controlRect.Left + "," + controlRect.Top + "," + controlRect.Right + "," + controlRect.Bottom + "]");

                // 尝试截取控件图片并获取OCR结果
                string ocrResult = CaptureControlImage(imageControl, width, height);
                if (!string.IsNullOrEmpty(ocrResult))
                {
                    Console.WriteLine("✅ Image控件截图成功");
                    
                    // 输入验证码到Edit控件并点击按钮
                    bool inputSuccess = InputCaptchaAndSubmit(dialogWindow, ocrResult);
                    if (inputSuccess)
                    {
                        Console.WriteLine("✅ 验证码输入和提交成功");
                    }
                    else
                    {
                        Console.WriteLine("❌ 验证码输入或提交失败");
                    }
                }
                else
                {
                    Console.WriteLine("❌ Image控件截图失败或OCR识别失败");
                }

                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("❌ 获取Image控件异常: " + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 截取控件图片并返回OCR识别结果
        /// </summary>
        static string CaptureControlImage(IntPtr controlHandle, int width, int height)
        {
            try
            {
                Console.WriteLine("📷 正在截取控件图片...");

                // 获取控件的设备上下文
                IntPtr controlDC = GetDC(controlHandle);
                if (controlDC == IntPtr.Zero)
                {
                    Console.WriteLine("❌ 无法获取控件设备上下文");
                    return "";
                }

                // 创建兼容的内存设备上下文
                IntPtr memoryDC = CreateCompatibleDC(controlDC);
                if (memoryDC == IntPtr.Zero)
                {
                    ReleaseDC(controlHandle, controlDC);
                    Console.WriteLine("❌ 无法创建内存设备上下文");
                    return "";
                }

                // 创建兼容的位图
                IntPtr bitmap = CreateCompatibleBitmap(controlDC, width, height);
                if (bitmap == IntPtr.Zero)
                {
                    DeleteDC(memoryDC);
                    ReleaseDC(controlHandle, controlDC);
                    Console.WriteLine("❌ 无法创建兼容位图");
                    return "";
                }

                // 选择位图到内存设备上下文
                IntPtr oldBitmap = SelectObject(memoryDC, bitmap);

                // 首先尝试使用WM_PRINT消息让控件绘制自己
                const uint WM_PRINT = 0x0317;
                const uint PRF_CLIENT = 0x00000004;
                const uint PRF_ERASEBKGND = 0x00000008;
                const uint PRF_CHILDREN = 0x00000010;
                const uint PRF_NONCLIENT = 0x00000002;
                
                uint printFlags = PRF_CLIENT | PRF_ERASEBKGND | PRF_CHILDREN | PRF_NONCLIENT;
                
                Console.WriteLine("🎨 使用WM_PRINT消息绘制控件...");
                IntPtr printResult = SendMessage(controlHandle, WM_PRINT, memoryDC, (IntPtr)printFlags);
                
                bool captureSuccess = false;
                
                // 如果WM_PRINT失败，尝试传统的BitBlt方法
                if (printResult == IntPtr.Zero)
                {
                    Console.WriteLine("⚠️ WM_PRINT失败，尝试BitBlt方法...");
                    captureSuccess = BitBlt(memoryDC, 0, 0, width, height, controlDC, 0, 0, SRCCOPY);
                }
                else
                {
                    Console.WriteLine("✅ WM_PRINT成功");
                    captureSuccess = true;
                }

                if (captureSuccess)
                {
                    Console.WriteLine("✅ 控件图片数据获取成功");
                    Console.WriteLine("📊 图片信息: " + width + "x" + height + " 像素");
                    
                                    // 保存图片到临时文件夹（使用memoryDC而不是controlDC）
                string savedFile = SaveBitmapToTempFolder(bitmap, memoryDC, width, height);
                if (!string.IsNullOrEmpty(savedFile))
                {
                    Console.WriteLine("💾 图片已保存到: " + savedFile);
                    
                    // 立即进行OCR识别
                    string recognizedText = RecognizeTextWithTesseract(savedFile);
                    if (!string.IsNullOrEmpty(recognizedText))
                    {
                        Console.WriteLine("🎯 验证码识别结果: " + recognizedText);
                        return recognizedText;
                    }
                    else
                    {
                        Console.WriteLine("⚠️ 验证码识别失败，请手动查看图片");
                        return "";
                    }
                }
                else
                {
                    Console.WriteLine("❌ 图片保存失败");
                    return "";
                }
                }
                else
                {
                    Console.WriteLine("❌ 控件图片数据获取失败");
                    return "";
                }

                // 清理资源
                SelectObject(memoryDC, oldBitmap);
                DeleteObject(bitmap);
                DeleteDC(memoryDC);
                ReleaseDC(controlHandle, controlDC);

                return "";
            }
            catch (Exception ex)
            {
                Console.WriteLine("❌ 截取控件图片异常: " + ex.Message);
                return "";
            }
        }

        /// <summary>
        /// 保存位图到Windows临时文件夹
        /// </summary>
        static string SaveBitmapToTempFolder(IntPtr bitmap, IntPtr hdc, int width, int height)
        {
            try
            {
                Console.WriteLine("💾 正在保存图片到临时文件夹...");

                // 获取Windows临时文件夹路径
                StringBuilder tempPath = new StringBuilder(260);
                uint result = GetTempPath(260, tempPath);
                if (result == 0)
                {
                    Console.WriteLine("❌ 无法获取临时文件夹路径");
                    return "";
                }

                // 生成唯一的文件名
                string fileName = "ImageControl_" + DateTime.Now.ToString("yyyyMMdd_HHmmss_fff") + ".bmp";
                string fullPath = tempPath.ToString() + fileName;
                Console.WriteLine("📂 临时文件夹: " + tempPath.ToString());
                Console.WriteLine("📄 文件名: " + fileName);

                // 使用.NET的Bitmap类保存文件（简化方法）
                bool saveSuccess = SaveBitmapUsingDotNet(bitmap, hdc, width, height, fullPath);
                
                if (saveSuccess)
                {
                    return fullPath;
                }
                else
                {
                    return "";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("❌ 保存位图到临时文件夹异常: " + ex.Message);
                return "";
            }
        }

        /// <summary>
        /// 使用.NET方法保存位图
        /// </summary>
        static bool SaveBitmapUsingDotNet(IntPtr hBitmap, IntPtr hdc, int width, int height, string filePath)
        {
            try
            {
                // 创建BITMAPINFO结构
                BITMAPINFO bmi = new BITMAPINFO();
                bmi.bmiHeader.biSize = (uint)Marshal.SizeOf(typeof(BITMAPINFOHEADER));
                bmi.bmiHeader.biWidth = width;
                bmi.bmiHeader.biHeight = -height; // 负值，从上到下存储，避免翻转
                bmi.bmiHeader.biPlanes = 1;
                bmi.bmiHeader.biBitCount = 32; // 32位彩色，包含Alpha通道
                bmi.bmiHeader.biCompression = 0; // BI_RGB
                bmi.bmiHeader.biSizeImage = 0;

                // 计算图像数据大小
                int stride = width * 4; // 32位 = 4字节每像素，已经是4字节对齐
                int imageSize = stride * height;
                
                // 分配内存存储图像数据
                byte[] imageData = new byte[imageSize];
                IntPtr imageDataPtr = Marshal.AllocHGlobal(imageSize);

                try
                {
                    // 获取位图数据
                    uint scanLines = GetDIBits(hdc, hBitmap, 0, (uint)height, imageDataPtr, ref bmi, DIB_RGB_COLORS);
                    if (scanLines == 0)
                    {
                        Console.WriteLine("❌ 无法获取位图数据");
                        return false;
                    }

                    // 复制数据到托管数组
                    Marshal.Copy(imageDataPtr, imageData, 0, imageSize);

                    // 直接写入BMP文件（使用负高度值，无需翻转）
                    bool writeSuccess = WriteBmpFile(filePath, width, height, imageData);
                    return writeSuccess;
                }
                finally
                {
                    Marshal.FreeHGlobal(imageDataPtr);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("❌ 使用.NET保存位图异常: " + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 写入BMP文件
        /// </summary>
        static bool WriteBmpFile(string filePath, int width, int height, byte[] imageData)
        {
            try
            {
                using (var fs = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
                using (var writer = new System.IO.BinaryWriter(fs))
                {
                    int stride = width * 4; // 32位 = 4字节每像素
                    int imageSize = stride * height;
                    int fileSize = 54 + imageSize; // 文件头(14) + 信息头(40) + 图像数据

                    // BMP文件头 (14字节)
                    writer.Write((ushort)0x4D42); // "BM"
                    writer.Write((uint)fileSize);   // 文件大小
                    writer.Write((uint)0);          // 保留字段
                    writer.Write((uint)54);         // 数据偏移

                    // BMP信息头 (40字节)
                    writer.Write((uint)40);         // 信息头大小
                    writer.Write((int)width);       // 图像宽度
                    writer.Write((int)-height);     // 图像高度（负值，从上到下）
                    writer.Write((ushort)1);        // 颜色平面数
                    writer.Write((ushort)32);       // 每像素位数（32位）
                    writer.Write((uint)0);          // 压缩类型
                    writer.Write((uint)imageSize);  // 图像数据大小
                    writer.Write((int)0);           // X像素每米
                    writer.Write((int)0);           // Y像素每米
                    writer.Write((uint)0);          // 使用的颜色数
                    writer.Write((uint)0);          // 重要颜色数

                    // 写入图像数据
                    writer.Write(imageData);
                }

                Console.WriteLine("✅ BMP文件写入成功");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("❌ 写入BMP文件异常: " + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 垂直翻转图像数据（修正BMP镜像问题）
        /// </summary>
        static byte[] FlipImageVertically(byte[] imageData, int width, int height, int stride)
        {
            try
            {
                Console.WriteLine("🔄 正在翻转图像数据修正镜像...");
                
                byte[] flippedData = new byte[imageData.Length];
                
                // 逐行复制，但是顺序相反
                for (int y = 0; y < height; y++)
                {
                    int sourceRowStart = y * stride;
                    int destRowStart = (height - 1 - y) * stride;
                    
                    // 复制一整行数据
                    Array.Copy(imageData, sourceRowStart, flippedData, destRowStart, stride);
                }
                
                Console.WriteLine("✅ 图像数据翻转完成");
                return flippedData;
            }
            catch (Exception ex)
            {
                Console.WriteLine("❌ 翻转图像数据异常: " + ex.Message);
                return imageData; // 返回原数据
            }
        }

        /// <summary>
        /// 使用Tesseract OCR识别图片中的文字
        /// </summary>
        static string RecognizeTextWithTesseract(string imagePath)
        {
            try
            {
                Console.WriteLine("🔍 正在使用Tesseract OCR识别验证码...");
                Console.WriteLine("📄 图片路径: " + imagePath);
                
                // 创建Process来调用tesseract命令
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = "tesseract";
                startInfo.Arguments = "\"" + imagePath + "\" stdout --psm 8 -c tessedit_char_whitelist=0123456789";
                startInfo.UseShellExecute = false;
                startInfo.RedirectStandardOutput = true;
                startInfo.RedirectStandardError = true;
                startInfo.CreateNoWindow = true;
                
                using (Process process = Process.Start(startInfo))
                {
                    if (process != null)
                    {
                        // 读取输出结果
                        string output = process.StandardOutput.ReadToEnd();
                        string error = process.StandardError.ReadToEnd();
                        
                        process.WaitForExit();
                        
                        if (process.ExitCode == 0)
                        {
                            string recognizedText = output.Trim();
                            Console.WriteLine("✅ OCR识别成功: " + recognizedText);
                            return recognizedText;
                        }
                        else
                        {
                            Console.WriteLine("❌ Tesseract执行失败:");
                            Console.WriteLine("错误信息: " + error);
                            return "";
                        }
                    }
                    else
                    {
                        Console.WriteLine("❌ 无法启动Tesseract进程");
                        return "";
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("❌ OCR识别异常: " + ex.Message);
                Console.WriteLine("💡 请确保Tesseract已正确安装并添加到PATH环境变量");
                return "";
            }
        }


        /// <summary>
        /// 使用键盘模拟输入文本
        /// </summary>
        static void SendKeys(string text)
        {
            try
            {
                Console.WriteLine("⌨️ 正在使用键盘模拟输入: " + text);
                
                foreach (char c in text)
                {
                    if (char.IsDigit(c))
                    {
                        byte vkCode = (byte)(VK_0 + (c - '0'));
                        
                        // 按下键
                        keybd_event(vkCode, 0, 0, UIntPtr.Zero);
                        
                        // 释放键
                        keybd_event(vkCode, 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
  
                    }
                    else
                    {
                        Console.WriteLine("⚠️ 跳过非数字字符: " + c);
                    }
                }
                
                Console.WriteLine("✅ 键盘输入完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine("❌ 键盘输入异常: " + ex.Message);
            }
        }

        /// <summary>
        /// 输入验证码到Edit控件并点击提交按钮
        /// </summary>
        static bool InputCaptchaAndSubmit(IntPtr dialogWindow, string captchaText)
        {
            try
            {
                Console.WriteLine("📝 正在输入验证码: " + captchaText);
                
                // 首先确保对话框窗口是激活状态
                Console.WriteLine("🔍 激活对话框窗口...");
                SetForegroundWindow(dialogWindow);

                
                // 查找AutomationId=2404的Edit控件
                IntPtr editControl = FindControlByAutomationId(dialogWindow, 2404);
                if (editControl == IntPtr.Zero)
                {
                    Console.WriteLine("❌ 未找到AutomationId=2404的Edit控件");
                    return false;
                }
                
                Console.WriteLine("✅ 找到Edit控件: 0x" + editControl.ToString("X"));
                
                // 设置焦点到Edit控件 - 使用鼠标点击方式
                Console.WriteLine("🎯 正在设置焦点到Edit控件...");
                
                RECT editRect;
                if (GetWindowRect(editControl, out editRect))
                {
                    int centerX = (editRect.Left + editRect.Right) / 2;
                    int centerY = (editRect.Top + editRect.Bottom) / 2;
                    
                    SetCursorPos(centerX, centerY);

                    mouse_event(0x0002, 0, 0, 0, UIntPtr.Zero); // MOUSEEVENTF_LEFTDOWN

                    mouse_event(0x0004, 0, 0, 0, UIntPtr.Zero); // MOUSEEVENTF_LEFTUP
                   
                }
                else
                {
                    Console.WriteLine("❌ 无法获取Edit控件位置");
                }
        
                
                // 清空现有内容（使用Ctrl+A全选然后删除）
                Console.WriteLine("🧹 清空现有内容...");
                keybd_event(VK_CONTROL, 0, 0, UIntPtr.Zero);
                keybd_event(VK_A, 0, 0, UIntPtr.Zero);
                keybd_event(VK_A, 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
                keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
      
                
                // 删除选中的内容
                keybd_event(VK_DELETE, 0, 0, UIntPtr.Zero);
                keybd_event(VK_DELETE, 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
                
                // 使用键盘模拟输入验证码
                Console.WriteLine("⌨️ 开始键盘模拟输入...");
                SendKeys(captchaText);
                Thread.Sleep(300);
                
                Console.WriteLine("✅ 验证码输入完成");
                
                // 查找AutomationId=1的Button控件
                IntPtr buttonControl = FindControlByAutomationId(dialogWindow, 1);
                if (buttonControl == IntPtr.Zero)
                {
                    Console.WriteLine("❌ 未找到AutomationId=1的Button控件");
                    return false;
                }
                
                Console.WriteLine("✅ 找到Button控件: 0x" + buttonControl.ToString("X"));
                
                // 点击按钮
                Console.WriteLine("🖱️ 正在点击提交按钮...");
                SendMessage(buttonControl, BM_CLICK, IntPtr.Zero, IntPtr.Zero);
            
                
                Console.WriteLine("✅ 按钮点击完成");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("❌ 输入验证码和提交异常: " + ex.Message);
                return false;
            }
        }
    }
}
